/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package savet.repositorio;

import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.commons.collections.list.SetUniqueList;
import savet.entidades.Ementa;
import savet.repositorio.exceptions.NonexistentEntityException;
import savet.repositorio.exceptions.PreexistingEntityException;

/**
 *
 * @author Rafael
 */
public class EmentaJpaController implements IRepositorioEmenta {

    public EmentaJpaController() {
        emf = Persistence.createEntityManagerFactory("SAVETPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Ementa ementa) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(ementa);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findEmenta(ementa.getEmenta()) != null) {
                throw new PreexistingEntityException("Ementa " + ementa + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Ementa ementa) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ementa = em.merge(ementa);
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = ementa.getEmenta();
                if (findEmenta(id) == null) {
                    throw new NonexistentEntityException("The ementa with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Ementa ementa;
            try {
                ementa = em.getReference(Ementa.class, id);
                ementa.getEmenta();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The ementa with id " + id + " no longer exists.", enfe);
            }
            em.remove(ementa);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Ementa> findEmentaEntities() {
        return findEmentaEntities(true, -1, -1);
    }

    public List<Ementa> findEmentaEntities(int maxResults, int firstResult) {
        return findEmentaEntities(false, maxResults, firstResult);
    }

    private List<Ementa> findEmentaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Ementa.class));
            Query q = em.createQuery(cq);

            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Ementa findEmenta(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Ementa.class, id);
        } finally {
            em.close();
        }
    }

    public int getEmentaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Ementa> rt = cq.from(Ementa.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

    public List getNativeQuery(String nativeQuery) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Ementa.class));
            Query q = em.createNativeQuery(nativeQuery);


            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public List getPorPropiedade(String nomePropiedade, Object valorPropiedade) {
        EntityManager em = getEntityManager();
        try {

            Query q = em.createNamedQuery("Ementa.findByTipo");
            q.setParameter(nomePropiedade, valorPropiedade);
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public LinkedList<String> getGrupos() {
        List<String> list = getNativeQuery("select Grupo from tblementario");

        SetUniqueList list1 = SetUniqueList.decorate(list);
        SortedSet<String> sortedSet = new TreeSet(list1.asSet());

        LinkedList<String> linkedList = new LinkedList<String>();
        LinkedList<String> linkedList2 = new LinkedList<String>();
        for (String string : sortedSet) {
            if (!string.startsWith("NR-")) {
                linkedList.add(string);
            } else {
                linkedList2.add(string);
            }
        }

        linkedList.addAll(linkedList2);
        return linkedList;
    }

    public static void main(String[] args) {
        EmentaJpaController controller = new EmentaJpaController();

        LinkedList<String> linkedList = controller.getGrupos();

        System.out.print("new String[]{");
        for (String string : linkedList) {
            System.out.print(",\"" + string + "\"");
        }
        System.out.print("} \n dsadsa");
    }
}
